package org.example.controller;

import com.google.common.collect.ImmutableMap;
import org.example.dto.*;
import org.example.entity.SysUser;
import org.example.model.PageBean;
import org.example.service.SysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private SysUserService sysUserService;

    //添加数据
    @PreAuthorize("hasAnyAuthority('sys:user:add')")
    @PostMapping
    public String add(@RequestBody AddUserDto addUserDto) {
        System.out.println(addUserDto);
        sysUserService.addUser(addUserDto);
        return "success";
    }

    //删除数据
    @PreAuthorize("hasAnyAuthority('sys:user:delete')")
    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable("id") Integer id) {
        System.out.println("删除");
        sysUserService.delete(id);
        return ImmutableMap.of("code", 1, "msg", "success");

    }

    //渲染数据
    @PreAuthorize("hasAnyAuthority('sys:user:view')")
    @GetMapping
    public PageBean<SysUser> getAll(@RequestParam(defaultValue = "1") Integer page,
                                    @RequestParam(defaultValue = "5") Integer size,
                                    @RequestParam(value = "name") String name,
                                    @RequestParam(value = "email") String email,
                                    @RequestParam(value = "mobile") String mobile) {

        return sysUserService.getPageData(page,size,name,email,mobile);
    }

    //改变状态
    @GetMapping("/cs/{id}")
    public void getStatus(@PathVariable("id") Integer id) {
        sysUserService.getStatus(id);
    }

    //获取编辑数据回显
    @GetMapping("/{id}")
    public EditUserDto getUserById(@PathVariable("id") Integer id) {
        EditUserDto editUser = sysUserService.getById(id);
        System.out.println("edit"+editUser);
        return editUser;
    }

    //编辑数据
    @PreAuthorize("hasAnyAuthority('sys:user:edit')")
    @PutMapping
    public String update(@RequestBody EditUserDto editUserDto) {
        sysUserService.editUser(editUserDto);
        System.out.println("修改");
        return "success";
    }

}
